package mya_dc.master_server.threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import mya_dc.master_server.database.ClientsHashTable;
import mya_dc.master_server.database.ServersHashTable;
import mya_dc.master_server.database.SlavesHashSet;

/**
 * a Thread manager for new server-threads
 *
 * @author      Adam Levi
 * <br>			MYA
 */
public class CompiServManager extends MYA_ThreadManager implements Runnable
{

	public CompiServManager(
			SlavesHashSet slavesArray,
			ClientsHashTable clientsArray,
			ServersHashTable compilationServers,
			ServerSocket serverSocket)
	{
		m_ServerSocket = serverSocket;
		m_SlavesArray = slavesArray;
		m_CompilationServers = compilationServers;
		m_ClientsArray = clientsArray;
	}
	
	@Override
	public void run()
	{
		acceptNewCompilationServers();
		try 
		{
			m_ServerSocket.close();
		}
		catch (IOException e)
		{
			//error - closing server
		}
	}

	private ServerSocket 		m_ServerSocket;
	private ClientsHashTable 	m_ClientsArray;
	private SlavesHashSet 		m_SlavesArray;
	private ServersHashTable	m_CompilationServers;
	
	private void acceptNewCompilationServers()
	{
		while(true)
		{
			Socket newCompServSocket = null;
			try
			{
				newCompServSocket = m_ServerSocket.accept();
				CompiServListenerThread tmp = new CompiServListenerThread(m_SlavesArray, m_ClientsArray, m_CompilationServers, newCompServSocket);
				m_Theards.add(tmp);
				new Thread(tmp).start();
			} 
			catch (IOException e)
			{
				try { m_ServerSocket.close(); }
				catch (IOException e1) { }
				doClose(); //closing clients
				break;
			}
			
		}
	}

}

